package com.iut2.projet2013;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

public class Bdd extends ContentProvider {

	private static final UriMatcher sUriMatcher;
	
	private static final int DEFAULT = 0;
	private static final int PEOPLE = 1;
	private static final int PICTURE = 2;
	private static final int PEOPLE_ID = 3;
	private static final int PICTURE_ID = 4;
	private static final int PEOPLE_ID_PICTURE = 5;
	private static final int PICTURE_ID_PEOPLE = 6;
	
	static {
		sUriMatcher=new UriMatcher(DEFAULT);
		sUriMatcher.addURI(Contract.AUTHORITY, Contract.People.TABLE_NAME, PEOPLE);
		sUriMatcher.addURI(Contract.AUTHORITY, Contract.Picture.TABLE_NAME, PICTURE);
		
		sUriMatcher.addURI(Contract.AUTHORITY, Contract.People.TABLE_NAME+"/#", PEOPLE_ID);
		sUriMatcher.addURI(Contract.AUTHORITY, Contract.Picture.TABLE_NAME+"/#", PICTURE_ID);
		
		sUriMatcher.addURI(Contract.AUTHORITY, Contract.People.TABLE_NAME+"/#/"+Contract.People.Picture.CONTENT_PATH, PEOPLE_ID_PICTURE);
		sUriMatcher.addURI(Contract.AUTHORITY, Contract.Picture.TABLE_NAME+"/#/"+Contract.Picture.People.CONTENT_PATH, PICTURE_ID_PEOPLE);
	}

	
	
	private static class AnnotDBHelper extends SQLiteOpenHelper {

		static final int VERSION=1;
		static final String DBNAME="picannot.db";
		
		public AnnotDBHelper(Context context) {
			super(context, DBNAME, null, VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(	"CREATE TABLE "+Contract.People.TABLE_NAME+ " ( "+
        			Contract.People._ID+" INTEGER PRIMARY KEY, " +
        			Contract.People.URI+" TEXT UNIQUE NOT NULL" +
        			")");
        db.execSQL(	"CREATE TABLE "+Contract.Picture.TABLE_NAME+ " ( "+
    			Contract.People._ID+" INTEGER PRIMARY KEY, " +
    			Contract.People.URI+" TEXT UNIQUE NOT NULL" +
    			")");
        
        db.execSQL(	"CREATE TABLE "+Contract.Annotation.TABLE_NAME+ " ( "+
    			Contract.Annotation.PEOPLE_ID+" INTEGER REFERENCES "+Contract.People.TABLE_NAME+"("+Contract.People._ID+"), " + 
    			Contract.Annotation.PICTURE_ID+" INTEGER REFERENCES "+Contract.Picture.TABLE_NAME+"("+Contract.Picture._ID+"), " +
    			" PRIMARY KEY ("+Contract.Annotation.PEOPLE_ID+","+Contract.Annotation.PICTURE_ID+"))");
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	private AnnotDBHelper dbHelper;
	
	@Override
	public boolean onCreate() {
		dbHelper=new AnnotDBHelper(this.getContext());
		return true;
	}
	
	
	@Override
	public String getType(Uri uri) {
		
		switch (sUriMatcher.match(uri)) {
			case PEOPLE: return Contract.People.CONTENT_TYPE;
			case PICTURE: return Contract.Picture.CONTENT_TYPE;
			case PEOPLE_ID: return Contract.People.CONTENT_ITEM_TYPE;
			case PICTURE_ID: return Contract.Picture.CONTENT_ITEM_TYPE;
			case PEOPLE_ID_PICTURE: return Contract.Picture.CONTENT_TYPE;
			case PICTURE_ID_PEOPLE: return Contract.People.CONTENT_TYPE;
			default: throw new IllegalArgumentException("Unknown Uri : "+uri.toString());
		}
	}
	
	
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}



	@Override
	public Uri insert(Uri uri, ContentValues values) {
		
		String tableName=null;
		Uri newUri=null;
		
		switch (sUriMatcher.match(uri)) {
			case PEOPLE:
				tableName=Contract.People.TABLE_NAME;
				break;
			case PEOPLE_ID_PICTURE:
				// Cas ou l'utilisateur fourni l'Uri externe de l'image
				String imgExternalUri = values.getAsString(Contract.People.Picture.URI);
				long imgId=-1;
				if (imgExternalUri!=null) {
					// il faut rŽcupŽrer l'id de l'image dans la table picture
					Cursor c =this.getContext().getContentResolver().query(Contract.Picture.CONTENT_URI, 
							new String[]{Contract.Picture._ID}, 
							Contract.Picture.URI+"=?", 
							new String[]{imgExternalUri}, null);
					if (c.moveToFirst()) {
						// cas ou l'image existe dans la table picture
						imgId = c.getLong(0);
					}
					// la l'image n'existe pas dans ma BD locale, il faut la crŽer
					else {
						Uri uriImg = this.getContext().getContentResolver().insert(Contract.Picture.CONTENT_URI, values);
						imgId = ContentUris.parseId(uriImg);
					}
				}
				values.remove(Contract.People.Picture.URI);
				values.put(Contract.Annotation.PICTURE_ID, imgId);
				// je rŽcupre l'id du contact ˆ partir de l'URI passŽe en paramtre
				long peopleId = Long.parseLong(uri.getPathSegments().get(1));
				values.put(Contract.Annotation.PEOPLE_ID, peopleId);
				tableName=Contract.Annotation.TABLE_NAME;
				newUri=Uri.withAppendedPath(uri, String.valueOf(imgId));
				
				break;
				
			default : throw new IllegalArgumentException("Unknown Uri : "+uri.toString());
		}
		
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		long id = db.insert(tableName, null, values);
		
		if (id>-1 && newUri==null){
			// L'uri de la  ligne crŽŽe est la concatŽnation de l'uri de base +"/"+id gŽnŽrŽ
			newUri=Uri.withAppendedPath(uri, String.valueOf(id));
		}
		return newUri;
	}



	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		String tableName=null;
		switch (sUriMatcher.match(uri)) {
			case PICTURE:
				tableName=Contract.Picture.TABLE_NAME;
				break;
			default : throw new IllegalArgumentException("Unknown Uri : "+uri.toString());
		}
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		return db.query(tableName, projection, selection, selectionArgs, null, null, sortOrder);
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}


}